package com.tx.studentManager.controller;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.tx.common.format.util.DateUtil;
import com.tx.studentManager.config.SystemConfig;
import com.tx.studentManager.model.ErrorInfo;
import com.tx.studentManager.model.Page;
import com.tx.studentManager.model.Student;
import com.tx.studentManager.model.StudentClass;
import com.tx.studentManager.qo.StudentQO;
import com.tx.studentManager.service.StudentClassService;
import com.tx.studentManager.service.StudentService;
import com.tx.studentManager.utils.DWZJsonUtil;

/**
 * 
 * @描述 学生管理控制器
 * @since studentManager-admin 1.0
 * @version 1.0 2015-9-14 上午10:03:32
 * @author 此生唯晴
 */
@Controller
@RequestMapping(value = "/student")
public class StudentController {
	@Autowired
	private StudentService studentService;
	@Autowired
	private StudentClassService classService;
	@Autowired
	private SystemConfig systemConfig;

	/**
	 * 
	 * @描述 查询学生信息
	 * @param qo
	 * @param pageNo
	 * @param pageSize
	 * @param createDateStartStr
	 * @param createDateEndStr
	 * @return
	 */
	@RequestMapping(value = "/list")
	public ModelAndView list(@ModelAttribute StudentQO qo,
			@RequestParam(required = false) Integer pageNo,
			@RequestParam(required = false) Integer pageSize,
			@RequestParam(required = false) String createDateStartStr,
			@RequestParam(required = false) String createDateEndStr) {
		if (StringUtils.isNotBlank(createDateEndStr)) {
			qo.setCreateDateEnd(DateUtil.str2DateTime(createDateEndStr));
		}
		if (StringUtils.isNotBlank(createDateStartStr)) {
			qo.setCreateDateStart(DateUtil.str2DateTime(createDateStartStr));
		}
		pageNo = pageNo == null ? 1 : pageNo;
		pageSize = pageSize == null ? systemConfig.getQueryPageSize()
				: pageSize;
		Page page = new Page();
		page.setPageNo(pageNo);
		page.setPageSize(pageSize);
		page.setCondition(qo);
		studentService.list(page);
		ModelAndView modelAndView = new ModelAndView("student/studentList");
		List<StudentClass> classList = classService.findAll();
		modelAndView.addObject("classList",classList);
		modelAndView.addObject("page", page);
		return modelAndView;
	}

	/**
	 * 
	 * @描述 修改学生信息
	 * @param studentId
	 * @return
	 */
	@RequestMapping("/modify")
	public ModelAndView modify(Integer studentId) {
		ModelAndView modelAndView = new ModelAndView("student/studentModify");
		Student student = studentService.findById(studentId);
		if (student == null) {
			ErrorInfo errorInfo = new ErrorInfo();
			errorInfo.setErrorMsg("未找到该学生，请查证后再试！");
			modelAndView.addObject(errorInfo);
		} else {
			List<StudentClass> classList = classService.findAll();
			modelAndView.addObject("classList",classList);
			modelAndView.addObject(student);
		}
		return modelAndView;
	}

	/**
	 * 
	 * @描述 修改学生信息
	 * @param student
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/update", produces = "text/html;charset=UTF-8")
	public String update(@ModelAttribute Student student,@RequestParam(required=true)String createDateStr) {
		Date createDate=DateUtil.str2DateTime(createDateStr);
		student.setCreateDate(createDate);
		boolean result = studentService.update(student);
		if (result) {
			return DWZJsonUtil.simpleJsonStr(DWZJsonUtil.RESULT_SUCCESS_CODE,
					"修改成功", DWZJsonUtil.OPER_CLOSE_CURRENT, "studentManager");
		} else {
			return DWZJsonUtil.simpleJsonStr(DWZJsonUtil.RESULT_SUCCESS_CODE,
					"修改成功", DWZJsonUtil.OPER_CLOSE_CURRENT, "studentManager");
		}
	}

	/**
	 * 
	 * @描述 返回添加学生视图
	 * @return
	 */
	@RequestMapping("/add")
	public ModelAndView add() {
		ModelAndView modelAndView = new ModelAndView("student/studentAdd");
		List<StudentClass> classList = classService.findAll();
		modelAndView.addObject("classList", classList);
		return modelAndView;
	}

	/**
	 * 
	 * @描述 添加学生
	 * @param student
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/toAdd", produces = "text/html;charset=UTF-8")
	public String toAdd(@ModelAttribute Student student, String classId) {
		if (StringUtils.isNotBlank(classId)) {
			StudentClass studentClass = classService.findById(classId);
			student.setStudentClass(studentClass);
		}
		student = studentService.insert(student);
		if (student == null) {
			DWZJsonUtil.simpleJsonStr(DWZJsonUtil.RESULT_FAILURE_CODE, "操作失败",
					DWZJsonUtil.OPER_CLOSE_CURRENT, "studentManager");
		}
		return DWZJsonUtil.simpleJsonStr(DWZJsonUtil.RESULT_SUCCESS_CODE,
				"添加成功", DWZJsonUtil.OPER_CLOSE_CURRENT, null);
	}

	/**
	 * 
	 * @描述 删除用户，物理删除
	 * @param studentId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/delete", produces = "text/html;charset=UTF-8")
	public String deleteStu(Integer studentId) {
		boolean result = studentService.delete(studentId);
		if (result) {
			return DWZJsonUtil.simpleJsonStr(DWZJsonUtil.RESULT_SUCCESS_CODE,
					"删除成功！", null, "studentManager");
		} else {
			return DWZJsonUtil.simpleJsonStr(DWZJsonUtil.RESULT_FAILURE_CODE,
					"删除失败！！！", null, null);
		}
	}
	/**
	 * 
	 * @描述 批量删除学生 
	 * @param ids
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/deleteAll",produces="text/html;charset=UTF-8")
	public String deleteAll(@RequestParam List<Integer> ids){
		
		String hql="delete from Student s where s.id in(:list)";
		if(studentService.batchExecuteWithHql(hql, ids)>0){
			return DWZJsonUtil.simpleJsonStr(DWZJsonUtil.RESULT_SUCCESS_CODE,
					"删除成功！", null, "studentManager");
		}else {
			return DWZJsonUtil.simpleJsonStr(DWZJsonUtil.RESULT_FAILURE_CODE,
					"删除失败！", null, null);
		}
		
	}
	/**
	 * 
	* @描述 导出学生信息 
	* @param qo
	* @param request
	* @param response
	* @param pageNo
	* @param pageSize
	* @param createDateStartStr
	* @param createDateEndStr
	 */
	@ResponseBody
	@RequestMapping(value="/export",produces="application/octet-stream;charset=utf-8")
	public void export(@ModelAttribute StudentQO qo,
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(required = false) Integer pageNo,
			@RequestParam(required = false) Integer pageSize,
			@RequestParam(required = false) String createDateStartStr,
			@RequestParam(required = false) String createDateEndStr){
		if (StringUtils.isNotBlank(createDateEndStr)) {
			qo.setCreateDateEnd(DateUtil.str2DateTime(createDateEndStr));
		}
		if (StringUtils.isNotBlank(createDateStartStr)) {
			qo.setCreateDateStart(DateUtil.str2DateTime(createDateStartStr));
		}
		
		String fileName="学生信息"+DateUtil.date2SeriaString(new Date())+".xls";
		try {
			response.setHeader("Content-Disposition", "attachment; filename="+new String(fileName.getBytes("utf-8"),"iso8859-1"));
		} catch (UnsupportedEncodingException e1) {
			response.setHeader("Content-Disposition", "attachment; filename="+DateUtil.date2SeriaString(new Date())+".xls");
		}
		Page page=new Page();
		
		page.setCondition(qo);
		studentService.list(page);
		@SuppressWarnings("unchecked")
		List<Student> studentList=(List<Student>) page.getList();
		HSSFWorkbook workbook=studentService.export(studentList);
		try {
			OutputStream out = response.getOutputStream();  
			workbook.write(out);
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}  
	}
}
